package com.ujson.chat.server.processor;

import com.ujson.base.common.utils.LogUtil;
import com.ujson.chat.common.proto.MessageProto;
import com.ujson.chat.server.builder.MessageResponseBuilder;
import com.ujson.chat.server.session.ServerSession;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <h3>ujson-parent</h3>
 * <p>聊天业务处理器</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-23 21:46
 */
@Slf4j
@Service
public class ChatProcessor {
    @Autowired
    private MessageResponseBuilder messageResponseBuilder;

    public MessageProto.Message messageRedirect(ChannelHandlerContext ctx, MessageProto.MessageRequest message) {
        String to = message.getTo();
        if (StringUtils.isNotBlank(to)) {
            if (ServerSession.USER_TO_CHANNEL_MAP.containsKey(to)) {
                ServerSession.USER_TO_CHANNEL_MAP.get(to).forEach(channel -> {
                    channel.writeAndFlush(MessageResponseBuilder.inst().build(ctx, message));
                });
                return messageResponseBuilder.commonBuild(ctx);
            } else {
                LogUtil.info(log, "user [" + to + "] is outline.");
            }
        } else {
            LogUtil.info(log, "target user not empty");
        }
        return messageResponseBuilder.commonBuild(ctx);
    }

}
